package com.jiazhong.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.backend.service.BookService;
import com.jiazhong.commons.Mapper.BookMapper;
import com.jiazhong.commons.Util.JsonResult;
import com.jiazhong.commons.Util.ResultTool;
import com.jiazhong.commons.bean.Book;
import com.jiazhong.commons.exception.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Override
    public JsonResult find(int page, int size) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.select("id","name","author","publisher","price");
        Page<Book> of = Page.of(page, size);
        List<Book> list = list(of,wrapper);
        of.setRecords(list);
        if (list==null||list.size()==0){
            throw new BookNotFoundException("没有找到该书籍");
        }
        return ResultTool.success(of);
    }

    @Override
    public JsonResult findSearch(String name, int page, int size) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.select("id","name","author","publisher","price");
        wrapper.like("name",name);
        Page<Book> of = Page.of(page, size);
        List<Book> list = list(of,wrapper);
        of.setRecords(list);
        if (list==null||list.size()==0){
            throw new BookNotFoundException("没有找到该书籍");
        }
        return ResultTool.success(of);
    }

    @Override
    public JsonResult saveBook(Book book) {
        boolean b = save(book);
        if (!b){
            throw new BookSaveException("添加数据错误");
        }
        return ResultTool.success("success");
    }

    @Override
    public JsonResult removeBook(String id) {
        boolean b = removeById(id);
        if (!b){
            throw new BookRemoveException("删除书籍失败");
        }
        return ResultTool.success("success");
    }

    @Override
    public JsonResult findExists(String column, String value) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.eq(column,value);
        wrapper.select("count(0)");
        Map<String,Object> map = getMap(wrapper);
        int row = Integer.parseInt(map.get("count(0)").toString());
        if (row==1){
            throw new BookExistsException(column+"已经存在");
        }
        return ResultTool.success("success");
    }
}
